package com.zhitan.ems.app.iot.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhitan.ems.app.iot.entity.GroupEntity;
import com.zhitan.ems.app.iot.mapper.GroupMapper;
import com.zhitan.ems.app.iot.service.GroupService;
import com.zhitan.ems.app.iot.vo.GroupVO;
import com.zhitan.ems.app.iot.vo.TreeGroupSelect;
import com.zhitan.ems.app.iot.wrapper.GroupWrapper;
import com.zhitan.ems.common.utils.StringUtils;
import com.zhitan.ems.framework.core.mp.base.BaseServiceImpl;
import com.zhitan.ems.framework.core.vo.VQueryKit;

@Service
public class GroupServiceImpl extends BaseServiceImpl<GroupMapper, GroupEntity> implements GroupService {
	
	@Override
	public List<GroupEntity> getFirstGroup() {
		QueryWrapper<GroupEntity> queryWrapper = new QueryWrapper<GroupEntity>();
		queryWrapper.eq("parent_group_id",0);
		List<GroupEntity> list = this.list(queryWrapper);
		return list;
	}
	
	/**
	 * 查询部门树结构信息
	 * @param dept 部门信息
	 * @return 部门树信息集合
	 */
	@Override
	public List<TreeGroupSelect> selectGroupreeList(Map<String, Object> params) {
		QueryWrapper<GroupEntity> queryWrapper = VQueryKit.getQueryWrapperByMap(params, Arrays.asList("name"),
				GroupEntity.class);
		queryWrapper.like(StringUtils.isNotNull(params.get("name")),"group_name", params.get("name"));
		queryWrapper.orderByDesc("group_order");
		List<GroupEntity> list = this.list(queryWrapper);
		List<GroupVO> groups = GroupWrapper.build().listVO(list);
		
		// 构建树形结构
		List<GroupVO> treeGroups = buildGroupTree(groups);
		
		// 如果传入了parentGroupId参数，则构建以该节点为根的子树
		Object parentGroupIdObj = params.get("parentGroupId");
		if (parentGroupIdObj != null) {
			Long parentGroupId = null;
			if (parentGroupIdObj instanceof Long) {
				parentGroupId = (Long) parentGroupIdObj;
			} else if (parentGroupIdObj instanceof String) {
				try {
					parentGroupId = Long.parseLong((String) parentGroupIdObj);
				} catch (NumberFormatException e) {
					// 如果转换失败，保持parentGroupId为null
				}
			}
			
			if (parentGroupId != null) {
				// 查找指定的父节点及其所有子节点
				List<GroupVO> subtreeGroups = findSubtreeGroups(treeGroups, parentGroupId);
				return buildGroupTreeSelect(subtreeGroups);
			}
		}
		return buildGroupTreeSelect(treeGroups);
	}

	/**
	 * 构建前端所需要下拉树结构
	 * 
	 * @param depts 部门列表
	 * @return 下拉树结构列表
	 */
	@Override
	public List<TreeGroupSelect> buildGroupTreeSelect(List<GroupVO> groups) {
		return groups.stream().map(TreeGroupSelect::new).collect(Collectors.toList());
	}

	@Override
	public List<GroupVO> buildGroupTree(List<GroupVO> groups) {
		List<GroupVO> returnList = new ArrayList<GroupVO>();
		List<Long> tempList = groups.stream().map(GroupVO::getGroupId).collect(Collectors.toList());
		for (GroupVO dept : groups) {
			// 如果是顶级节点, 遍历该父节点的所有子节点
			if (!tempList.contains(dept.getParentGroupId())) {
				recursionFn(groups, dept);
				returnList.add(dept);
			}
		}
		if (returnList.isEmpty()) {
			returnList = groups;
		}
		return returnList;
	}

	/**
	 * 递归列表
	 */
	private void recursionFn(List<GroupVO> list, GroupVO t) {
		// 得到子节点列表
		List<GroupVO> childList = getChildList(list, t);
		t.setChildren(childList);
		for (GroupVO tChild : childList) {
			if (hasChild(list, tChild)) {
				recursionFn(list, tChild);
			}
		}
	}

	/**
	 * 得到子节点列表
	 */
	private List<GroupVO> getChildList(List<GroupVO> list, GroupVO t) {
		List<GroupVO> tlist = new ArrayList<GroupVO>();
		Iterator<GroupVO> it = list.iterator();
		while (it.hasNext()) {
			GroupVO n = (GroupVO) it.next();
			if (StringUtils.isNotNull(n.getParentGroupId())
					&& n.getParentGroupId().longValue() == t.getGroupId().longValue()) {
				tlist.add(n);
			}
		}
		return tlist;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChild(List<GroupVO> list, GroupVO t) {
		return getChildList(list, t).size() > 0;
	}

	/**
	 * 查找以指定节点为根的子树所有节点
	 * @param allGroups 所有分组
	 * @param parentGroupId 父节点ID
	 * @return 子树中的所有节点
	 */
	private List<GroupVO> findSubtreeGroups(List<GroupVO> allGroups, Long parentGroupId) {
		List<GroupVO> result = new ArrayList<>();
		
		// 先找到根节点
		GroupVO root = allGroups.stream()
				.filter(group -> group.getGroupId() != null && group.getGroupId().equals(parentGroupId))
				.findFirst()
				.orElse(null);
				
		if (root != null) {
			// 添加根节点
			result.add(root);
			// 递归添加所有子节点
			addChildren(result, allGroups, root.getGroupId());
		}
		
		return result;
	}
	
	/**
	 * 递归添加子节点
	 * @param result 结果列表
	 * @param allGroups 所有分组
	 * @param parentId 父节点ID
	 */
	private void addChildren(List<GroupVO> result, List<GroupVO> allGroups, Long parentId) {
		List<GroupVO> children = allGroups.stream()
				.filter(group -> group.getParentGroupId() != null && group.getParentGroupId().equals(parentId))
				.collect(Collectors.toList());
				
		result.addAll(children);
		
		// 递归处理子节点的子节点
		for (GroupVO child : children) {
			addChildren(result, allGroups, child.getGroupId());
		}
	}
}